/**
 * @author: enic
 * @date: 2018-04-10
 * @desc: 练习数据库访问
 */


import java.sql.Connection;  
import java.sql.DriverManager;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.Statement; 


//import java.sql.*;

/**
 * @author enic
 *
 */
public class MainTestEntry {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			System.out.println("start !");
			
			String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
			String dbUrl = "jdbc:sqlserver://192.168.16.23:1433;DatabaseName=QPAccountsDB";
			
			String userName = "sa";  
			String userPwd  = "sa";
			
			// 这个大概是动态import一个名字叫driverName的类
			Class.forName(driverName);
			Connection conn = null;
			conn = DriverManager.getConnection(dbUrl, userName, userPwd);
			if(null == conn) {
				System.out.println("connect faild !");
			}
			else {
				System.out.println("connect !");
			}
			
			String sqlCmd = "SELECT * FROM AccountsInfo;";
			Statement stat = conn.createStatement();
			ResultSet rs = stat.executeQuery(sqlCmd);
			
			while(rs.next()) {
				System.out.println(rs.getString("UserID") + "," + rs.getString("NickName") + "," + rs.getDate("RegisterDate"));
			}
			
			rs.close();
			
			// 推荐的更加安全的访问方式
			PreparedStatement preStat = conn.prepareStatement(sqlCmd);
			rs = preStat.executeQuery();
			while(rs.next()) {
				System.out.println(rs.getString("UserID") + "," + rs.getString("NickName") + "," + rs.getDate("RegisterDate"));
			}
			
			rs.close();
			
			conn.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

}
